package com.base.service;

import java.util.*;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import tool.StringTool;
import tool.TimeTool;

import com.base.bean.*;
import com.base.dao.*;
import com.base.service.AddressService.ADD_TYPE;


/**
 * SyncService and SyncService2用于将result表中的对应了销售员的客户生成为。。。
 * @author Administrator
 *
 */
public class SyncService {

	private volatile static SyncService instance = null;
	private ResultDao resultDao;
	
	private SyncService(){
		resultDao = (ResultDao) _BaseDao.ac.getBean("ResultDao");
	}
	
	public static SyncService getInstance() {
		if (instance == null) {
			synchronized (SyncService.class) {// 1
				if (instance == null) {// 2
					instance = new SyncService();// 3
				}
			}
		}
		return instance;
	}
	
	
	
	
	
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SyncService ss=SyncService.getInstance();
		
		for(int i=0;i<5000;i++){
			List<Result> list=ss.getData(i*100,100);
			if(list.size()==0)
				break;
			for(Result r:list){
				
				if(r.getState()==21){
					Integer creatorId=r.getUid();
					String memo=r.getMemo();
					String name=r.getA1();
					String phone1=r.getA2();
					String province=r.getA4();
					String city=r.getA5();
					String area=r.getA6();			
					ss.addForSync(creatorId, memo, name, phone1,province,city,area);
				}
			}
			
			System.out.println("已处理"+i*100+"条");
		}
		
		System.out.println("END");
		
		
		
	}
	
	
	private List<Result> getData(int offset,int pageSize){
		return resultDao.findByPage("from Result r where r.state=21", offset, pageSize);
	}
	
	
	
	private int addForSync(Integer creatorId,String memo,String name,String phone1,String province,String city,String area) {
		
		String tip="";
		Integer cid=0;
		Integer phone1Id=0;
		Integer oppType=1;
		
		//验证电话是否重复
		if(ClientService.getInstance().checkPhone(phone1)<1){
			tip="电话重复或格式错误";
			System.out.println(tip);
			return -3;
		}
		
		
		boolean isOwn = false;
		ClientBase cb = null;
		List<ClientPhone> cps = null;
		
		
		// clientExtend 无论如何都可以写入（不管是否是由自己创建的）
		ClientExtend ce = new ClientExtend();
		ce.setCid(0);
		ce.setModified(TimeTool.getSyncTime());
		ce.setMemo(memo);
		ce.setOwner(creatorId);
		
		cb = new ClientBase();
		cb.setCid(0);
		cb.setCrmFlag(1);		
		cb.setProvince(province);
		cb.setCity(city);
		cb.setArea(area);
		
		

		cb.setName(name);
		
		cb.setModified(TimeTool.getSyncTime());
		cb.setCreator(creatorId);
		cb.setOwner(creatorId);
		cb.setState(1);

		cps = new ArrayList<ClientPhone>();
		ClientPhone cp1 = new ClientPhone();
		cp1.setCid(0);
		cp1.setCreator(creatorId);
		cp1.setOwner(creatorId);
		cp1.setState(1);
		cp1.setPhone(phone1);
		cp1.setId(phone1Id);
		cp1.setCreated(TimeTool.getSyncTime());

		cps.add(cp1);		

		ClientExtend ce0 = null;
		Session session = ClientService.getInstance().getClientBaseDao()
				.getSessionFactory().getCurrentSession();
		Criteria criteria = null;
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			// add start
			
				cb.setCreated(TimeTool.getSyncTime());
				cb.setOwner(creatorId);
				cb.setOriginId(0); // 非推荐客户
				cb.setCrmFlag(1);
				session.save(cb);
				@SuppressWarnings("unchecked")
				List<Integer> results = session
						.createCriteria(ClientBase.class)
						.setMaxResults(1)
						.setProjection(
								Projections.projectionList().add(
										Projections.max("cid"))

						).list();
				Integer maxId = results.get(0);

				ce.setId(0); // 会自动生成主键
				ce.setCreated(TimeTool.getSyncTime());
				ce.setCid(maxId);
				cid = maxId;
				ce.setState(1);
				session.merge(ce);

				for (ClientPhone p : cps) {
					if (p.getPhone().equals(""))
						continue;
					p.setCid(maxId); // 将cid写入
					p.setId(null);
					p.setOwner(creatorId);
					session.save(p);
				}

		 // add end
			

			tx.commit();
			tip = "添加成功！";
			return 1;
		} catch (Exception e) {
			tx.rollback();
			tip = "添加失败";
			e.printStackTrace();
			return -1; // 修改或添加失败
		} finally {
			if (session.isOpen())
				session.close();
		}
	}
	


}
